#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
邮件发送模块
"""
import smtplib
import os
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from . import config

# 确保配置已加载
from .config import load_config
if not config.sections():
    load_config()

# 发送邮件
def send_email(to_email: str, subject: str, body: str):
    # 检查SMTP配置
    try:
        EMAIL = config.get('EMAIL', 'smtp_user')  # 发送方邮箱
        EMAIL_PASSWORD = config.get('EMAIL', 'smtp_password')  # 发送方邮箱密码
        EMAIL_SERVER = config.get('EMAIL', 'smtp_server')
        EMAIL_PORT = config.get('EMAIL', 'smtp_port')
    except Exception as e:
        print(f"读取邮件配置时发生异常: {e}")
        print(f"配置文件路径: {os.path.abspath('config/config.ini')}")
        print(f"配置节: {config.config.sections()}")
        return False
    
    # 检查必要的配置是否为空
    if not all([EMAIL, EMAIL_PASSWORD, EMAIL_SERVER, EMAIL_PORT]):
        print(f"[警告] SMTP配置不完整，无法发送邮件。请检查config.ini文件中的[EMAIL]部分。")
        print(f"  - smtp_user: {EMAIL}")
        print(f"  - smtp_password: {'***' if EMAIL_PASSWORD else '空'}")
        print(f"  - smtp_server: {EMAIL_SERVER}")
        print(f"  - smtp_port: {EMAIL_PORT}")
        return False
    
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = EMAIL
    msg['To'] = to_email
    msg['Subject'] = subject
    # 添加邮件正文
    msg.attach(MIMEText(body, 'html', 'utf-8'))

    try:
        # 连接到SMTP服务器
        server = smtplib.SMTP_SSL(EMAIL_SERVER, int(EMAIL_PORT))  # 根据你的邮箱提供商更改SMTP服务器地址和端口
        # 开启debug模式
        # server.set_debuglevel(1)
        # 登录到SMTP服务器
        server.login(EMAIL, EMAIL_PASSWORD)

        # 发送邮件
        server.sendmail(EMAIL, to_email, msg.as_string())
        server.quit()
        print("邮件投递成功!")
        print(f"发送邮件到 {to_email}: {subject}")
        print(f"邮件内容: {body}")
    except Exception as e:
        print(f"邮件投递失败!,失败原因: {e}")
        return False
    return True

# def send_email(to_email: str, subject: str, body: str):
#     """发送邮件（简化版，实际使用时需要配置SMTP）"""
#     # 这里是一个简化的邮件发送实现
#     # 实际使用时需要配置SMTP服务器
#     print(f"发送邮件到 {to_email}: {subject}")
#     print(f"邮件内容: {body}")
#     return True